<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="多线程," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="Android的AsyncTask比Handler更轻量级一些，适用于简单的异步处理。">
<meta property="og:type" content="article">
<meta property="og:title" content="AsyncTask介绍">
<meta property="og:url" content="http://yoursite.com/2017/02/28/201702/AsyncTask介绍/index.html">
<meta property="og:site_name" content="HoneyGuide's Blog">
<meta property="og:description" content="Android的AsyncTask比Handler更轻量级一些，适用于简单的异步处理。">
<meta property="og:updated_time" content="2017-02-28T13:47:56.116Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="AsyncTask介绍">
<meta name="twitter:description" content="Android的AsyncTask比Handler更轻量级一些，适用于简单的异步处理。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'R1W2VDDO1V',
      apiKey: '773854c4c250e5a5cf9cddd97ebcc167',
      indexName: 'Hexo_search',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/02/28/201702/AsyncTask介绍/"/>





  <title> AsyncTask介绍 | HoneyGuide's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">﻿<div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">HoneyGuide's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Stay hungry & Stay young</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">

　　　　　　<!--增加的代码 start-->

          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/02/28/201702/AsyncTask介绍/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="HoneyGuide">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="HoneyGuide's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                AsyncTask介绍
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-02-28T00:00:00+08:00">
                2017-02-28
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index">
                    <span itemprop="name">Android</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Android的AsyncTask比Handler更轻量级一些，适用于简单的异步处理。<br><a id="more"></a><br>首先明确Android之所以有Handler和AsyncTask，都是为了不阻塞主线程（UI线程），且UI的更新只能在主线程中完成，因此异步处理是不可避免的。</p>
<h3 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h3><p>Android为了降低这个开发难度，提供了AsyncTask。AsyncTask就是一个封装过的后台任务类，顾名思义就是异步任务。</p>
<h3 id="API"><a href="#API" class="headerlink" title="API"></a>API</h3><p>AsyncTask直接继承于Object类，位置为android.os.AsyncTask。要使用AsyncTask工作我们要提供三个泛型参数，并重载几个方法(至少重载一个)。</p>
<p>AsyncTask定义了三种泛型类型 Params，Progress和Result。</p>
<ul>
<li>Params 启动任务执行的输入参数，比如HTTP请求的URL。</li>
<li>Progress 后台任务执行的百分比。</li>
<li>Result 后台执行任务最终返回的结果，比如String。</li>
</ul>
<p>一个异步加载数据最少要重写以下这两个方法。</p>
<ul>
<li><strong>doInBackground(Params…)</strong><br>  后台执行，比较耗时的操作都可以放在这里。注意这里不能直接操作UI。此方法在后台线程执行，完成任务的主要工作，通常需要较长的时间。在执行过程中可以调用publicProgress(Progress…)来更新任务的进度。</li>
<li><strong>onPostExecute(Result)</strong> 相当于Handler<br>  处理UI的方式，在这里面可以使用在doInBackground 得到的结果处理操作UI。 此方法在主线程执行，任务执行的结果作为此方法的参数返回。</li>
</ul>
<p>有必要的话你还得重写以下这三个方法，但不是必须的。</p>
<ul>
<li>onProgressUpdate(Progress…)<br>  可以使用进度条增加用户体验度。此方法在主线程执行，用于显示任务执行的进度。</li>
<li>onPreExecute()<br>  这里是最终用户调用Excute时的接口，当任务执行之前开始调用此方法，可以在这里显示进度对话框。</li>
<li>onCancelled()<br>  用户调用取消时，要做的操作。</li>
</ul>
<p>使用AsyncTask类，以下是几条必须遵守的准则：</p>
<ul>
<li>Task的实例必须在UI thread中创建；</li>
<li>execute方法必须在UI thread中调用；</li>
<li>不要手动的调用onPreExecute(), onPostExecute(Result)，doInBackground(Params…), onProgressUpdate(Progress…)这几个方法；</li>
<li>该task只能被执行一次，否则多次调用时将会出现异常。</li>
</ul>
<h3 id="举例"><a href="#举例" class="headerlink" title="举例"></a>举例</h3><p>主Activity调用<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">button.setOnClickListener(new OnClickListener() &#123;  </div><div class="line">            @Override  </div><div class="line">            public void onClick(View v) &#123;  </div><div class="line">                ProgressBarAsyncTask asyncTask = new ProgressBarAsyncTask(textView, progressBar);  </div><div class="line">                asyncTask.execute(1000);  </div><div class="line">            &#125;  </div><div class="line">&#125;);</div></pre></td></tr></table></figure></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">//模拟网络环境  </div><div class="line">public class NetOperator &#123;  </div><div class="line">    public void operator()&#123;  </div><div class="line">        try &#123;  </div><div class="line">            //休眠1秒  </div><div class="line">            Thread.sleep(1000);  </div><div class="line">        &#125; catch (InterruptedException e) &#123;  </div><div class="line">            // TODO Auto-generated catch block  </div><div class="line">            e.printStackTrace();  </div><div class="line">        &#125;  </div><div class="line">    &#125;  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div></pre></td><td class="code"><pre><div class="line">/**  </div><div class="line"> * 生成该类的对象，并调用execute方法之后  </div><div class="line"> * 首先执行的是onProExecute方法  </div><div class="line"> * 其次执行doInBackgroup方法  </div><div class="line"> *  </div><div class="line"> */  </div><div class="line">public class ProgressBarAsyncTask extends AsyncTask&lt;Integer, Integer, String&gt; &#123;  </div><div class="line">  </div><div class="line">    private TextView textView;  </div><div class="line">    private ProgressBar progressBar;  </div><div class="line">      </div><div class="line">      </div><div class="line">    public ProgressBarAsyncTask(TextView textView, ProgressBar progressBar) &#123;  </div><div class="line">        super();  </div><div class="line">        this.textView = textView;  </div><div class="line">        this.progressBar = progressBar;  </div><div class="line">    &#125;  </div><div class="line">  </div><div class="line">  </div><div class="line">    /**  </div><div class="line">     * 这里的Integer参数对应AsyncTask中的第一个参数   </div><div class="line">     * 这里的String返回值对应AsyncTask的第三个参数  </div><div class="line">     * 该方法并不运行在UI线程当中，主要用于异步操作，所有在该方法中不能对UI当中的空间进行设置和修改  </div><div class="line">     * 但是可以调用publishProgress方法触发onProgressUpdate对UI进行操作  </div><div class="line">     */  </div><div class="line">    @Override  </div><div class="line">    protected String doInBackground(Integer... params) &#123;  </div><div class="line">        NetOperator netOperator = new NetOperator();  </div><div class="line">        int i = 0;  </div><div class="line">        for (i = 10; i &lt;= 100; i+=10) &#123;  </div><div class="line">            netOperator.operator();  </div><div class="line">            publishProgress(i);  </div><div class="line">        &#125;  </div><div class="line">        return i + params[0].intValue() + &quot;&quot;;  </div><div class="line">    &#125;  </div><div class="line">  </div><div class="line">  </div><div class="line">    /**  </div><div class="line">     * 这里的String参数对应AsyncTask中的第三个参数（也就是接收doInBackground的返回值）  </div><div class="line">     * 在doInBackground方法执行结束之后在运行，并且运行在UI线程当中 可以对UI空间进行设置  </div><div class="line">     */  </div><div class="line">    @Override  </div><div class="line">    protected void onPostExecute(String result) &#123;  </div><div class="line">        textView.setText(&quot;异步操作执行结束&quot; + result);  </div><div class="line">    &#125;  </div><div class="line">  </div><div class="line">  </div><div class="line">    //该方法运行在UI线程当中,并且运行在UI线程当中 可以对UI空间进行设置  </div><div class="line">    @Override  </div><div class="line">    protected void onPreExecute() &#123;  </div><div class="line">        textView.setText(&quot;开始执行异步线程&quot;);  </div><div class="line">    &#125;  </div><div class="line">  </div><div class="line"> </div><div class="line">    /**  </div><div class="line">     * 这里的Intege参数对应AsyncTask中的第二个参数  </div><div class="line">     * 在doInBackground方法当中，，每次调用publishProgress方法都会触发onProgressUpdate执行  </div><div class="line">     * onProgressUpdate是在UI线程中执行，所有可以对UI空间进行操作  </div><div class="line">     */  </div><div class="line">    @Override  </div><div class="line">    protected void onProgressUpdate(Integer... values) &#123;  </div><div class="line">        int vlaue = values[0];  </div><div class="line">        progressBar.setProgress(vlaue);  </div><div class="line">    &#125;  </div><div class="line">  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="AsyncTask两种线程池"><a href="#AsyncTask两种线程池" class="headerlink" title="AsyncTask两种线程池"></a>AsyncTask两种线程池</h3><p>1、THREAD_POOL_EXECUTOR，<strong>异步</strong>线程池</p>
<p>首先创建一个继承自AsyncTask的MyAsyncTask类，然后调用。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">MyAsyncTask asynct = new MyAsyncTask(task);</div><div class="line">asynct.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, 0);</div></pre></td></tr></table></figure></p>
<p>当一个任务通过此方法欲添加到线程池时：</p>
<ul>
<li>如果此时线程池中的数量小于corePoolSize，即使线程池中的线程都处于空闲状态，也要创建新的线程来处理被添加的任务。</li>
<li>如果此时线程池中的数量等于 corePoolSize，但是缓冲队列 workQueue未满，那么任务被放入缓冲队列。</li>
<li>如果此时线程池中的数量大于corePoolSize，缓冲队列workQueue满，并且线程池中的数量小于maximumPoolSize，建新的线程来处理被添加的任务。</li>
<li>如果此时线程池中的数量大于corePoolSize，缓冲队列workQueue满，并且线程池中的数量等于maximumPoolSize，那么通过 handler所指定的策略来处理此任务。</li>
<li>当线程池中的线程数量大于 corePoolSize时，如果某线程（非核心线程）空闲时间超过keepAliveTime，线程将被终止。这样，线程池可以动态的调整池中的线程数。</li>
</ul>
<p>也就是：处理任务的优先级为：<br><strong>核心线程corePoolSize、任务队列workQueue、最大线程maximumPoolSize</strong>，如果三者都满了，使用handler处理被拒绝的任务（一般为抛出java.util.concurrent.RejectedExecutionException异常）。</p>
<p>2、SERIAL_EXECUTOR，<strong>同步</strong>线程池  </p>
<p>它是默认的Executor，所以可以直接调用，所以可以有两种调用方法。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">asynct.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, 0);</div><div class="line">asynct.execute(0);</div></pre></td></tr></table></figure></p>
<p>SERIAL_EXECUTOR在THREAD_POOL_EXECUTOR的基础上添加了一个mTasks的集合来保证任务顺序执行。</p>
<h3 id="AsyncTask和Handler的比较"><a href="#AsyncTask和Handler的比较" class="headerlink" title="AsyncTask和Handler的比较"></a>AsyncTask和Handler的比较</h3><ul>
<li>AsyncTask<ul>
<li>优点：是一个轻量级的异步任务处理类，轻量级体现在，使用方便、代码简洁上，而且整个异步任务的过程可以通过cancel()进行控制；</li>
<li>缺点：不适用于处理长时间的异步任务，一般这个异步任务的过程最好控制在几秒以内，如果是长时间的异步任务就需要考虑多线程的控制问题；当处理多个异步任务时，UI更新变得困难。</li>
</ul>
</li>
<li>Handler<ul>
<li>优点：代码结构清晰，容易处理多个异步任务；</li>
<li>缺点：当有多个异步任务时，由于要配合Thread或Runnable，代码可能会稍显冗余。</li>
</ul>
</li>
</ul>
<p>总之，AsyncTask不失为一个非常好用的异步任务处理类，只要不是频繁对大量UI进行更新，可以考虑使用；而Handler在处理大量UI更新时可以考虑使用。</p>
<h3 id="AsyncTask缺陷"><a href="#AsyncTask缺陷" class="headerlink" title="AsyncTask缺陷"></a>AsyncTask缺陷</h3><ul>
<li>生命周期</li>
</ul>
<p>关于AsyncTask存在一个这样广泛的误解，很多人认为一个在Activity中的AsyncTask会随着Activity的销毁而销毁。然后事实并非如此。AsyncTask会一直执行doInBackground()方法直到方法执行结束。一旦上述方法结束，会依据情况进行不同的操作。</p>
<p>如果cancel(boolean)调用了，则执行onCancelled(Result)方法</p>
<p>如果cancel(boolean)没有调用，则执行onPostExecute(Result)方法</p>
<p>AsyncTask的cancel方法需要一个布尔值的参数，参数名为mayInterruptIfRunning,意思是如果正在执行是否可以打断,如果这个值设置为true，表示这个任务可以被打断，否则，正在执行的程序会继续执行直到完成。如果在doInBackground()方法中有一个循环操作，我们应该在循环中使用isCancelled()来判断，如果返回为true，我们应该避免执行后续无用的循环操作。</p>
<p>总之，我们使用AsyncTask需要确保AsyncTask正确地取消。</p>
<ul>
<li>不好好工作的cancel()</li>
</ul>
<p>如果你调用了AsyncTask的cancel(false)，doInBackground()仍然会执行到方法结束，只是不会去调用onPostExecute()方法。但是实际上这是让应用程序执行了没有意义的操作。</p>
<p>那么是不是我们调用cancel(true)前面的问题就能解决呢？并非如此。如果mayInterruptIfRunning设置为true，会使任务尽早结束，但是如果的doInBackground()有不可打断的方法会失效，比如这个BitmapFactory.decodeStream() IO操作。但是你可以提前关闭IO流并捕获这样操作抛出的异常。但是这样会使得cancel()方法没有任何意义。</p>
<ul>
<li>内存泄露</li>
</ul>
<p>还有一种常见的情况就是，在Activity中使用非静态匿名内部AsyncTask类，由于Java内部类的特点，AsyncTask内部类会持有外部类的隐式引用。由于AsyncTask的生命周期可能比Activity的长，当Activity进行销毁AsyncTask还在执行时，由于AsyncTask持有Activity的引用，导致Activity对象无法回收，进而产生内存泄露。</p>
<ul>
<li>结果丢失</li>
</ul>
<p>另一个问题就是在屏幕旋转等造成Activity重新创建时AsyncTask数据丢失的问题。当Activity销毁并重新创建后，还在运行的AsyncTask会持有一个Activity的非法引用即之前的Activity实例。导致onPostExecute()没有任何作用。</p>
<h3 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h3><p><a href="http://www.cnblogs.com/devinzhang/archive/2012/02/13/2350070.html" target="_blank" rel="external">http://www.cnblogs.com/devinzhang/archive/2012/02/13/2350070.html</a><br><a href="http://www.2cto.com/kf/201606/518662.html" target="_blank" rel="external">http://www.2cto.com/kf/201606/518662.html</a><br><a href="http://bbs.51cto.com/thread-1114378-1.html" target="_blank" rel="external">http://bbs.51cto.com/thread-1114378-1.html</a><br><a href="http://blog.csdn.net/boyupeng/article/details/49001215" target="_blank" rel="external">http://blog.csdn.net/boyupeng/article/details/49001215</a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/多线程/" rel="tag"># 多线程</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/02/28/201702/OOM问题/" rel="next" title="OOM问题">
                <i class="fa fa-chevron-left"></i> OOM问题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/01/201703/Handler/" rel="prev" title="Handler">
                Handler <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="HoneyGuide" />
          <p class="site-author-name" itemprop="name">HoneyGuide</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">29</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              
                <span class="site-state-item-count">34</span>
                <span class="site-state-item-name">标签</span>
              
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#定义"><span class="nav-number">1.</span> <span class="nav-text">定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#API"><span class="nav-number">2.</span> <span class="nav-text">API</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#举例"><span class="nav-number">3.</span> <span class="nav-text">举例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AsyncTask两种线程池"><span class="nav-number">4.</span> <span class="nav-text">AsyncTask两种线程池</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AsyncTask和Handler的比较"><span class="nav-number">5.</span> <span class="nav-text">AsyncTask和Handler的比较</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AsyncTask缺陷"><span class="nav-number">6.</span> <span class="nav-text">AsyncTask缺陷</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参考"><span class="nav-number">7.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HoneyGuide</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  





  



  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="local-search-pop-overlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


  

</body>
</html>
